package com.sjk.flink.util;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.internal.JsonContext;
import com.sjk.flink.ExpireStreamProcess;
import com.sjk.flink.correct.IfCorrectRule;
import com.sjk.flink.correct.rules.*;
import com.sjk.flink.exeception.BaseException;
import com.sjk.flink.exeception.ErrorCode;
import com.sjk.flink.functions.JsonValidationProcessFunction;
import com.sjk.flink.pojo.JzField;
import com.sjk.flink.pojo.JzPojo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 校准数据
 */
public final class JzValueUtils {

    private final static Map<String, IfCorrectRule> ZJ_MAPS= new HashMap<>();

    static {
        TrueFalseRuler trueFalse = new TrueFalseRuler();
        ZJ_MAPS.put(trueFalse.getName(),trueFalse);

        UnifyDateTimeRuler unifyDateTimeRuler = new UnifyDateTimeRuler();
        ZJ_MAPS.put(unifyDateTimeRuler.getName(),unifyDateTimeRuler);

        IntegerRuler integerRuler = new IntegerRuler();
        ZJ_MAPS.put(integerRuler.getName(),integerRuler);

        FloatRuler floatRuler = new FloatRuler();
        ZJ_MAPS.put(floatRuler.getName(),floatRuler);

        DoubleRuler doubleRuler = new DoubleRuler();
        ZJ_MAPS.put(doubleRuler.getName(),doubleRuler);

        //强制转换为String
        StringRuler stringRuler = new StringRuler();
        ZJ_MAPS.put(stringRuler.getName(),stringRuler);

        FtpUrlRuler ftpUrlRuler = new FtpUrlRuler();
        ZJ_MAPS.put(ftpUrlRuler.getName(),ftpUrlRuler);
    }

    public static JzPojo jsonhander(Map<String,String> JZZL_CONFIGS, String key, String json){
        JzPojo jzpojo = new JzPojo();
        jzpojo.setSuccess(false);
        jzpojo.setJson(json);
        jzpojo.setSkip(true);
        String jzzlConfig = JZZL_CONFIGS.get(key);
        if(jzzlConfig==null||jzzlConfig.isEmpty()){
            //不做校准
            return jzpojo;
        }

        jzpojo.setSkip(false);
        List<JzField> fields = new ArrayList<JzField>();
        try {
            List<String> paths = JsonPath
                    .using(Configuration.builder().options(Option.AS_PATH_LIST).build())
                    .parse(jzzlConfig)
                    .read("$..ruleType", List.class);
            //查询所有的  $..*
            //只查询ruleType的  $..*
            //System.out.println(">>>>>>>>>>>>>  " + paths.size());
            // compile paths
            List<JsonPath> jsonPaths = paths
                    .stream()
                    .map(p -> JsonPath.compile(p))
                    .collect(Collectors.toList());

            //质量校准配置
            JsonContext document1 = (JsonContext) JsonPath.parse(jzzlConfig.toString());
            //需要校准的文件
            JsonContext document = (JsonContext) JsonPath.parse(json);
            jsonPaths.forEach(path -> {
                String pathStr = path.getPath();
                //System.out.println("pathStr >>>>>>>>>>>>>>>>>>>> " + pathStr);
                String ruleType = document1.read(path, String.class);
                //System.out.println("ruleType >>>>>>>>>>>>>>>>>>>> " + ruleType);
                IfCorrectRule correctRule = ZJ_MAPS.get(ruleType);
                if (correctRule == null) {
                    throw new BaseException(ErrorCode.CODE_E00003.getCode(),ErrorCode.CODE_E00003.getMsg());
                }
                //获得父节点
                JzField field = new JzField();
                String parentpath = pathStr.replace("['ruleType']", "");
                try {
                    JsonPath p = JsonPath.compile(parentpath);   //根据表达式找到该节点
                    //原来值不知道什么类型
                    Object value = document.read(p);
                    field.setValue(value);
                    //System.out.println("原来的值   >>>>>>>>>>>>>>>>>>>>   " + value);
                    document.set(p, correctRule.transformValue(value));
                }catch (Exception ex){
                    if(!(ex instanceof PathNotFoundException)){
                        System.out.println("校准失败： "+parentpath);
                        field.setField(parentpath);
                        field.setErrorCode(ErrorCode.CODE_E00008.getCode());
                        field.setErrorMesasge("校对字段："+parentpath+",原始值:"+field.getValue()+",校准错误信息："+ExecptionUtil.getStackTraceMsg(ex));
                        fields.add(field);
                    }
                }
            });
            jzpojo.setFields(fields);
            if(fields.size()>0){
                jzpojo.setSuccess(false);
            }else{
                jzpojo.setSuccess(true);
            }
            jzpojo.setJson(document.jsonString());
            return jzpojo;
        }catch (Exception ex){
            //出错不做校准
            System.out.println("校准解析错误："+ex.getMessage());
            jzpojo.setSuccess(false);
            jzpojo.setFields(fields);
            jzpojo.setErrorCode(ErrorCode.CODE_E00007.getCode());
            jzpojo.setErrorMesasge(ExecptionUtil.getStackTraceMsg(ex));
            return jzpojo;
        }
    }
}
